<template>
  <div class="app-container home">
    <!--    <el-dialog-->
    <!--      title="添加"-->
    <!--      :visible.sync="isEdit"-->
    <!--      width="30%"-->
    <!--      :before-close="handleClose">-->
    <!--        <el-form>-->
    <!--          -->
    <!--        </el-form>-->
    <!--      <span slot="footer" class="dialog-footer">-->
    <!--    <el-button @click="isEdit = false">取 消</el-button>-->
    <!--    <el-button type="primary" @click="submit">确 定</el-button>-->
    <!--  </span>-->
    <!--    </el-dialog>-->
    <el-container>
      <el-header style="padding: 0; height: auto;">  
        <el-card>  
          <div style="font-size: 21px; font-weight: bolder;">  
            非金属夹杂物成分转换  
          </div>  
        </el-card>  
      </el-header>
      <!--  --------------------------------------------------------------------------------------------第一个表格控件  -->
      <el-container style="margin-top: 20px;">
        <el-aside width="250px" style="height: 365px; padding: 0.3% 0.3% 0.3% 0.3%; margin-right: 10px; background-color: #f5f7fa;">  
          <el-card style="height: 100%; margin-top: 0; background-color: transparent; box-shadow: none; max-height: 350px; overflow-y: auto;">  
            <div style="margin-top: 15px; text-align: center;">  
              <el-upload   
                class="upload"   
                action=""   
                :auto-upload="false"   
                :show-file-list="false"   
                :multiple="false"   
                :on-change="(file, fileList) => importTemp(file, fileList)"  
                >  
                <el-button type="primary" class="flex" style="width: 195px;">导入数据</el-button>  
              </el-upload>  
            </div>  
            <div style="margin-top: 20px; text-align: center;">  
              <el-button type="primary" @click="inputData" style="width: 100%;">输入数据</el-button>  
            </div>  
          </el-card>  
        </el-aside>
        <el-main style="margin-top: 0; padding-top: 0; display: flex; align-items: center; justify-content: center; height: 100%;"> 
          <el-table
            @cell-click="tableDataClick"
            :data="tableData"
            style="width: 100%; margin-top: 0;border: 2px solid #d6e6f2; border-radius: 4px;"  
            height="365px"  
            border  
            highlight-current-row  
            align="center"  
            :row-key="getRowKey"> 

            <el-table-column
              align="center"
              prop="fileName"
              hidden="hidden"
              label="文件夹名"
              width="120">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.fileName"></el-input>
                <span v-else>{{ scope.row.fileName }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="index"
              label="夹杂物序号"
              width="100">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.index"></el-input>
                <span v-else>{{ scope.row.index }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Ca"
              label="Ca">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Ca"></el-input>
                <span v-else>{{ scope.row.Ca }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Ce"
              label="Ce">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Ce"></el-input>
                <span v-else>{{ scope.row.Ce }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Mg"
              label="Mg">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Mg"></el-input>
                <span v-else>{{ scope.row.Mg }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Al"
              label="Al">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Al"></el-input>
                <span v-else>{{ scope.row.Al }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Ti"
              label="Ti">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Ti"></el-input>
                <span v-else>{{ scope.row.Ti }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Li"
              label="Li">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Li"></el-input>
                <span v-else>{{ scope.row.Li }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Si"
              label="Si">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Si"></el-input>
                <span v-else>{{ scope.row.Si }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="B"
              label="B">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.B"></el-input>
                <span v-else>{{ scope.row.B }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="V"
              label="V">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.V"></el-input>
                <span v-else>{{ scope.row.V }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Mn"
              label="Mn">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Mn"></el-input>
                <span v-else>{{ scope.row.Mn }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Nb"
              label="Nb">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Nb"></el-input>
                <span v-else>{{ scope.row.Nb }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Cr"
              label="Cr">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Cr"></el-input>
                <span v-else>{{ scope.row.Cr }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Fe"
              label="Fe">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Fe"></el-input>
                <span v-else>{{ scope.row.Fe }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Na"
              label="Na">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Na"></el-input>
                <span v-else>{{ scope.row.Na }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="K"
              label="K">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.K"></el-input>
                <span v-else>{{ scope.row.K }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="C"
              label="C">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.C"></el-input>
                <span v-else>{{ scope.row.C }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="N"
              label="N">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.N"></el-input>
                <span v-else>{{ scope.row.N }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="O"
              label="O">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.O"></el-input>
                <span v-else>{{ scope.row.O }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="F"
              label="F">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.F"></el-input>
                <span v-else>{{ scope.row.F }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="S"
              label="S">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.S"></el-input>
                <span v-else>{{ scope.row.S }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Cl"
              label="Cl">
              <template slot-scope="scope">
                <el-input v-if="scope.row.isEditing" v-model="scope.row.Cl"></el-input>
                <span v-else>{{ scope.row.Cl }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              prop="Cz"
              width="180px"
              label="操作"
              fixed="right"
            >
              <template slot-scope="scope">
                <el-button
                  v-if="scope.row.isEditing"
                  type="primary"
                  size="mini"
                  @click="add(scope.row)"
                >
                  确认新增
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
      <!--  --------------------------------------------------------------------------------------------第二个表格控件  -->
      <el-container>
        <el-aside width="250px" style="height: 365px; padding: 0.3% 0.3% 0.3% 0.3%; margin-right: 10px; background-color: #f5f7fa;">  
          <el-card style="height: 100%; margin-top: 0; background-color: transparent; box-shadow: none; max-height: 350px; overflow-y: auto;">  
            <div style="margin-top: 15px; text-align: center;">  
              <el-button type="primary" @click="converter" style="width: 100%;">成分转换</el-button>  
            </div>  
            <div style="margin-top: 20px; text-align: center;">  
              <el-button type="primary" style="width: 100%;">保存数据</el-button>  
            </div>  
          </el-card>  
        </el-aside> 
        <el-main style="margin-top: 0; padding-top: 0;">
          <el-table
            :data="tableData1"
            style="width: 100%; margin-top: 0; max-width: 100%;   
            border: 2px solid #d6e6f2;   
            border-radius: 4px;"  
            height="365px"  
            border  
            highlight-current-row  
            align="center"  
            :row-key="getRowKey"
            :element-loading-text="'加载中'"  
            element-loading-spinner="el-icon-loading"  
            element-loading-background="rgba(0, 0, 0, 0.8)"
            >

            <el-table-column
              align="center"
              prop="fileName"
              hidden="hidden"
              label="文件夹名"
              width="120">
            </el-table-column>
            <el-table-column
              align="center"
              prop="index"
              label="夹杂物序号"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="CaF2"
              label="CaF2"
              width="90">
            </el-table-column>
            <el-table-column
              align="center"
              prop="CaO"
              label="CaO"
              width="90">
            </el-table-column>
            <el-table-column
              align="center"
              prop="CeO"
              label="CeO"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="MgO"
              label="MgO"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="Al2O3"
              label="Al2O3"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="Ti2O3"
              label="Ti2O3"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="Li2O"
              label="Li2O"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="SiO2"
              label="SiO2"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="B2O3"
              label="B2O3"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="V2O3"
              label="V2O3"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="MnO"
              label="MnO"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="NbO2"
              label="NbO2"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="Cr2O3"
              label="Cr2O3"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="FeO"
              label="FeO"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="Na2O"
              label="Na2O"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="K2O"
              label="K2O"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="TiN"
              label="TiN"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="AlN"
              label="AlN"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="CeS"
              label="CeS"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="TiS"
              label="TiS"
              width="100">
            </el-table-column>
            <el-table-column
              align="center"
              prop="MnS"
              label="MnS"
              width="100">
            </el-table-column>
          </el-table>
        </el-main>
      </el-container>
    </el-container>

    <el-container style="height: 600px; overflow: hidden;">  
      <el-header style="padding: 0; height: auto;">  
        <el-card>  
          <div style="font-size: 21px; font-weight: bolder;">  
            非金属夹杂物来源判断  
          </div>  
        </el-card>  
      </el-header>  
      
      <el-container style="margin-top: 15px; height: calc(100% - 80px);">  
        <!-- 左侧按钮和文本区域 -->  
        <el-aside width="250px" style="height: 500px; padding: 0.3% 0.3% 0.3% 0.3%; margin-right: 10px; background-color: #f5f7fa; ">  
          <el-card style="height: 100%; margin-top: 0; background-color: transparent; box-shadow: none; max-height: 500px; overflow-y: auto;">  
            <!-- 按钮区域 -->  
            <div style="margin-top: 5px; text-align: center">  
              <el-button type="primary" @click="handleSourceAnalysis" style="width: 100%;">夹杂物的来源</el-button>  
            </div>  
            <!-- 来源分析文本 - 使用sourceAnalysis控制显示/隐藏 -->  
            <div v-show="sourceAnalysis" style="margin-top: 10px; overflow-y: auto;">  
              <el-alert  
                title="来源分析"  
                :closable="false"  
                type="warning">  
              </el-alert>  
              <div style="font-size: 12px; white-space: pre-line; padding: 10px; border: 1px solid #eee; margin-top: 5px; background-color: white;">  
                <div v-html="analysisResult"></div> <!-- 单独的容器用于 HTML 渲染 --> 
              </div>  
            </div>  
            
            <!-- 解决方案按钮 -->  
            <div style="margin-top: 20px; text-align: center">  
              <el-button type="primary" @click="strategy=!strategy" style="width: 100%;">建议解决方案</el-button>  
            </div>  
            
            <!-- 解决方案文本 - 使用原有的strategy控制显示/隐藏 -->  
            <div v-show="strategy" style="margin-top: 10px;  overflow-y: auto;">  
              <el-alert  
                title="解决方案"  
                :closable="false"  
                type="warning">  
              </el-alert>  
              <div style="font-size: 12px; white-space: pre-line; padding: 10px; border: 1px solid #eee; margin-top: 5px; background-color: white;">  
                稳定拉速、稳定过热度、稳定浸入水口插入深度  
              </div>  
            </div>  
          </el-card>  
        </el-aside>

        <!-- 右侧双图表区域 -->  
        <el-main style="height: 500px; padding: 0.5% 1% 0.5% 1%; overflow: hidden; background-color: #e6f7ff; border: 2px dashed #1890ff;">  
          <el-card style="margin-top: 0; height: 100%; background-color: #f6ffed; border: 2px solid #c1f294; overflow: hidden;">  
            <!-- 左侧图表 -->  
            <div id="myChart" ref="chart" style="float: left; width: 49%; height: 440px; padding: 2px 2px 2px 2px; background-color: #fbffff; border: 1px solid #13c2c2;"></div>  
            
            <!-- 中间分隔线 -->  
            <div style="float: left; width: 2%; height: 400px; display: flex; justify-content: center; align-items: center;">  
              <div style="width: 1px; height: 100%; background-color: #ddd;"></div>  
            </div>  
            
            <!-- 右侧图表 -->  
            <div id="myChart2" ref="chart2" style="float: left; width: 49%; height: 440px; background-color: #fbffff; border: 1px solid #a0d911;"></div>  
          </el-card>
        </el-main>
      </el-container>  
    </el-container>
  </div>
</template>



<script>
import * as xlsx from 'xlsx';
import * as echarts from 'echarts';
import * as XLSX from "xlsx";
import axios from "axios";
import Plotly from 'plotly.js-dist'
import service from "@/utils/request";
import {add} from "core-js/internals/set-helpers";
export default {
  name: "Index",
  mounted(){
    this.initChart();
  },
  data() {
    return {
      // 版本号
      version: "3.8.8",
      tabPosition: 'left',
      tableData:[],
      tableData1:[],
      currentItem:{},
      echartsData:[],
      isEdit : false,
      strategy : false,
      sourceAnalysis: false,  // 新增：控制来源分析显示/隐藏
      analysisResult: ""      // 初始为空，等待API返回结果
    };
  },
  methods: {
    add(row) {
      // 找到当前编辑的行并将其添加到tableData中
      const index = this.tableData.indexOf(row);
      if (index !== -1) {
        this.tableData[index].isEditing = false; // 移除编辑状态
      }
    },
    getRowKey(row) {
      return row.index; // 或者使用其他唯一标识符
    },
    //  点击确定
    submit(){
      this.isEdit = false

    },

    handleClose(){
      this.tableData = []
      this.isEdit = false
    },
    //  点击输入       ////////////////////////////////////////////////////////////////////////////////
    inputData(){
      this.tableData.push({
        fileName: null,
        index: null,
        Ca: 0,
        Ce: 0,
        Mg: 0,
        Al: 0,
        Ti: 0,
        Li: 0,
        Si: 0,
        B: 0,
        V: 0,
        Mn: 0,
        Nb: 0,
        Cr: 0,
        Fe: 0,
        Na: 0,
        K: 0,
        C: 0,
        N: 0,
        O: 0,
        F: 0,
        S: 0,
        Cl: 0,
        isEditing: true
      });
    },

    //  某行被点击，用于成分转换  /////////////////////////////////////////////////////////////////////////////////////////////////////
    tableDataClick(row){
      this.currentItem = row;
      console.log(this.currentItem)
    },
    //    
    goTarget(href) {
      window.open(href, "_blank");
    },
    

    //  成分转换方法    //////////////////////////////////////////////////////////////////////////////////////////////////
    converter() {  
      if (Object.keys(this.currentItem).length !== 0) {  
        // 确保文件名被传递  
        var name = this.currentItem.fileName || 'Converted Data';  
        
        // 创建一个新的请求对象，确保包含文件名  
        let requestData = {...this.currentItem, fileName: name};  
        
        service.post('converter', requestData).then(res => {  
          var list = [];  
          if (res.converted_row) {  
            // 确保文件名存在  
            res.converted_row.fileName = name;  
            
            list.push(res.converted_row);  
            this.tableData1 = list;  
            
            this.$message.success("转换成功！");  
          } else {  
            this.$message.error("转换失败，未收到有效数据");  
          }  
        }).catch(error => {  
          console.error('转换出错:', error);  
          this.$message.error("转换失败，请检查数据");  
        });  
      } else {  
        if (this.tableData.length === 0) {  
          this.$message.warning("请先导入数据！");  
        } else {  
          this.$message.warning("请在导入数据的表格中选择一行进行成分转换！");  
        }  
      }  
    },
    //        导入数据    ///////////////////////////////////////////////////////////////////////////////////////////////
    importTemp(file, fileList) {  
      // 清空表格数据  
      this.tableData = []; // 清空之前的数据  
      
      if (!file.raw) {  
        console.error('文件对象无效');  
        return;  
      }  

      const fileReader = new FileReader();  
      
      fileReader.onload = (ev) => {  
        try {  
          const data = ev.target.result;  
          
          const workbook = XLSX.read(data, {   
            type: 'binary',  
            cellDates: true,  
            cellNF: false,  
            cellText: true   
          });  
          
          const sheetName = Object.keys(workbook.Sheets)[1] || Object.keys(workbook.Sheets)[0];  
          
          const worksheet = workbook.Sheets[sheetName];  
          
          const jsonData = XLSX.utils.sheet_to_json(worksheet, {   
            header: 1,  
            defval: '',  
            blankrows: false  
          });  
          
          if (!jsonData || !Array.isArray(jsonData) || jsonData.length === 0) {  
            console.error('未找到有效数据');  
            return;  
          }  
          
          const headers = jsonData[0];  
          
          const expectedHeaders = [  
            'index', 'Ca', 'Ce', 'Mg', 'Al', 'Ti',   
            'Li', 'Si', 'B', 'V', 'Mn',   
            'Nb', 'Cr', 'Fe', 'Na', 'K',   
            'C', 'N', 'O', 'F', 'S', 'Cl'  
          ];  
          
          jsonData.shift();  
          
          const columnMapping = {};  
          headers.forEach((header, index) => {  
            const matchedHeader = expectedHeaders.find(  
              expected => expected.trim().toLowerCase() === String(header).trim().toLowerCase()  
            );  
            
            if (matchedHeader) {  
              columnMapping[matchedHeader] = index;  
            }  
          });  
          
          // 添加自增 index  
          const processedData = jsonData.map((item, dataIndex) => {  
            const tableItem = {  
              // 使用当前总数据长度 + 1 作为自增索引    
              fileName: file.name.split('.')[0],  
              index: dataIndex + 1, // 自增索引   
              Ca: 0, Ce: 0, Mg: 0, Al: 0, Ti: 0,  
              Li: 0, Si: 0, B: 0, V: 0, Mn: 0,  
              Nb: 0, Cr: 0, Fe: 0, Na: 0, K: 0,  
              C: 0, N: 0, O: 0, F: 0, S: 0, Cl: 0  
            };  
            
            expectedHeaders.forEach(header => {  
              if (columnMapping.hasOwnProperty(header)) {  
                const columnIndex = columnMapping[header];  
                tableItem[header] = Number(item[columnIndex]) || 0;  
              }  
            });  
            
            return tableItem;  
          });  
          
          // 添加到表格数据  
          this.tableData.push(...processedData);  
          
        } catch (error) {  
          console.error('Excel处理错误:', error);  
          this.$message.error('Excel文件解析失败');  
        }  
      };  
      
      fileReader.onerror = (error) => {  
        console.error('文件读取错误:', error);  
        this.$message.error('文件读取失败');  
      };  
      
      fileReader.readAsBinaryString(file.raw);  
    },

    //    第二个图  三元相图   ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
      drawTernaryPlot() {  
        // 归一化处理  
        const normalizedData = this.tableData1.map(item => {  
            const total = item.CaO + item.Al2O3 + item.SiO2;  
            return {  
                ...item,  
                normalizedCaO: item.CaO / total,  
                normalizedAl2O3: item.Al2O3 / total,  
                normalizedSiO2: item.SiO2 / total  
            };  
        });  

        const data = [{  
            type: 'scatterternary',  
            mode: 'markers',  
            a: normalizedData.map(item => item.normalizedCaO),  
            b: normalizedData.map(item => item.normalizedAl2O3),  
            c: normalizedData.map(item => item.normalizedSiO2),  
            marker: {  
                size: 10,  
                color: this.tableData1.map(item => item.MgO),  
                colorscale: 'Viridis',  
                showscale: false  
            },  
            text: normalizedData.map(item =>  
                `CaO: ${item.CaO.toFixed(2)}% (归一化: ${(item.normalizedCaO * 100).toFixed(2)}%)<br>` +  
                `Al2O3: ${item.Al2O3.toFixed(2)}% (归一化: ${(item.normalizedAl2O3 * 100).toFixed(2)}%)<br>` +  
                `SiO2: ${item.SiO2.toFixed(2)}% (归一化: ${(item.normalizedSiO2 * 100).toFixed(2)}%)<br>` +  
                `MgO: ${item.MgO}%`  
            ),  
            hoverinfo: 'text',  
            hovertemplate: '%{text}<extra></extra>',   
            showlegend: true,  
            name: '数据点'  
        }];  

        // 计算平均值  
        const avgCaO = this.tableData1.reduce((sum, item) => sum + item.CaO, 0) / this.tableData1.length;  
        const avgAl2O3 = this.tableData1.reduce((sum, item) => sum + item.Al2O3, 0) / this.tableData1.length;  
        const avgSiO2 = this.tableData1.reduce((sum, item) => sum + item.SiO2, 0) / this.tableData1.length;  
        const avgMgO = this.tableData1.reduce((sum, item) => sum + item.MgO, 0) / this.tableData1.length;  
        
        const layout = {  
          paper_bgcolor: 'transparent',  
          plot_bgcolor: 'transparent',  
          title: {  
                text: '三元相图',  
                font: {   
                    family: 'Times New Roman',  
                    size: 16,  
                    color: 'black',  
                    weight: 'bold'  
                },  
                x: 0.5,  
                xanchor: 'center',  
                y: 0.95,  
                yanchor: 'top'  
            },  
            ternary: {   
                bgcolor: 'transparent',   
                aaxis: {  
                    title: {  
                        text: 'CaO',  
                        font: { size: 12 , family: "Times New Roman"}  
                    },  
                    min: 0,  
                    max: 1,  
                    showline: true,  
                    ticks: 'outside' ,
                    tickfont: {  
                        family: '"New Roman", "Times New Roman", serif'  
                    } 
                },  
                baxis: {  
                    title: {  
                        text: 'Al2O3',  
                        font: { size: 12, family: "Times New Roman"}  
                    },  
                    min: 0,  
                    max: 1,  
                    showline: true,  
                    ticks: 'outside',
                    tickfont: {  
                        family: '"New Roman", "Times New Roman", serif'  
                    }   
                },  
                caxis: {  
                    title: {  
                        text: 'SiO2',  
                        font: { size: 12 , family: "Times New Roman"}  
                    },  
                    min: 0,  
                    max: 1,  
                    showline: true,  
                    ticks: 'outside' ,
                    tickfont: {  
                        family: '"Times New Roman", serif'  
                    }
                }  
            },  
            showlegend: true,  
            legend: {  
                bgcolor: 'transparent',  
                title: {   
                    text: `详细成分信息:<br>` +   
                          `CaO:  ${avgCaO.toFixed(2)}%<br>` +   
                          `Al2O3:  ${avgAl2O3.toFixed(2)}%<br>` +   
                          `SiO2:  ${avgSiO2.toFixed(2)}%<br>` +   
                          `MgO:  ${avgMgO.toFixed(2)}%`,  
                    font: {   
                        size: 12,   
                        color: 'black' ,
                        family: "Times New Roman"
                    }  
                },  
                orientation: 'h',  
                x: 0.8,  
                y: 1.1,  
                xanchor: 'center',  
                yanchor: 'top'  
            }     
        };  

        // 绘制三元相图  
        Plotly.newPlot('myChart2', data, layout);  

        // 添加 MgO 含量标识  
        this.tableData1.forEach(item => {  
            const mgpData = item.MgO;  
            const coordinates = this.convertToTriangleCoord(  
                normalizedData.find(n => n.CaO === item.CaO).normalizedCaO,   
                normalizedData.find(n => n.Al2O3 === item.Al2O3).normalizedAl2O3,   
                normalizedData.find(n => n.SiO2 === item.SiO2).normalizedSiO2  
            );  
            
            Plotly.addAnnotation('myChart2', {  
                x: coordinates[0],  
                y: coordinates[1],  
                text: `MgO: ${mgpData}%`,  
                showarrow: true,  
                arrowhead: 2,  
                ax: 0,  
                ay: -40  
            });  
        });  
    },



    //    第一个图    ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    jzSource(){
      var item = this.tableData1[0]
      //业务逻辑
      this.echartsData = []
      this.echartsData.push(item.CaF2===null?0:item.CaF2)
      this.echartsData.push(item.CaO===null?0:item.CaO)
      this.echartsData.push(item.CeO===null?0:item.CeO)
      this.echartsData.push(item.MgO===null?0:item.MgO)
      this.echartsData.push(item.Al2O3===null?0:item.Al2O3)
      this.echartsData.push(item.Ti2O3===null?0:item.Ti2O3)
      this.echartsData.push(item.Li2O===null?0:item.Li2O)
      this.echartsData.push(item.TiO2===null?0:item.TiO2)
      this.echartsData.push(item.SiO2===null?0:item.SiO2)
      this.echartsData.push(item.B2O3===null?0:item.B2O3)
      this.echartsData.push(item.V2O3===null?0:item.V2O3)
      this.echartsData.push(item.MnO===null?0:item.MnO)
      this.echartsData.push(item.NbO2===null?0:item.NbO2)
      this.echartsData.push(item.Cr2O3===null?0:item.Cr2O3)
      this.echartsData.push(item.FeO===null?0:item.FeO)
      this.echartsData.push(item.Na2O===null?0:item.Na2O)
      this.echartsData.push(item.K2O===null?0:item.K2O)
      this.echartsData.push(item.TiN===null?0:item.TiN)
      this.echartsData.push(item.AlN===null?0:item.AlN)
      this.echartsData.push(item.Ces===null?0:item.Ces)
      this.echartsData.push(item.TiS===null?0:item.TiS)
      this.echartsData.push(item.MnS===null?0:item.MnS)
      this.updateChart();
      console.log(this.echartsData)
    },

    //    第一个图更新后的样子 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    updateChart() {
      const chart = echarts.init(this.$refs.chart, null, {  
        renderer: 'canvas',  
        devicePixelRatio: window.devicePixelRatio || 4 // 设置为设备像素比或更高以获得超清效果  
      }); 
      
      const option = {
        title: {  
          text: '夹杂物组成分布',  
          left: 'center',  // 水平居中  
          top: 10,         // 距顶部10px  
          textStyle: {  
            fontSize: 16,  
            fontWeight: 'bold'
          }  
        },  
        tooltip: {},
        legend: {},
        grid: {  
          left: '4%',    // 减小左边距  
          right: '4%',   // 减小右边距  
          bottom: '3%', // 为旋转的标签预留底部空间  
          top: '10%',     // 为标题预留顶部空间  
          containLabel: true, // 确保标签被包含在内  
          width: 'auto'  // 自动使用可用宽度  
        },  
        xAxis: {
          data: ["CaF2","CaO","CeO","MgO","Al2O3","Ti2O3","Li2O","TiO2","SiO2","B2O3","V2O3","MnO","NbO2","Cr2O3","FeO","Na2O","K2O","TiN","AlN","CeS","TiS","MnS"],  
          axisLabel: {  
            rotate: -45,  
            interval: 0,  
            align: 'left', 
            verticalAlign: 'top',     // 改为top来使标签向下移动  
            margin: 15,               // 增加margin使标签向下移动更多  
            offset: -40,              // 增大负offset值使标签向左移动更多  
            distance: 20,              // 增加距离与轴线的距离 
            fontFamily: '"Times New Roman", serif'
          } 
        },
        yAxis: {
          name: '百分比',
          axisLabel: {  
            fontFamily: '"Times New Roman", serif'
          } 
        },
        series: [{
          type: 'bar',
          data: this.echartsData
        }]
      };
      chart.setOption(option);
    },
    //    第一个图演示样子 ////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    initChart() {
      const chart = echarts.init(this.$refs.chart, null, {  
        renderer: 'canvas',  
        devicePixelRatio: window.devicePixelRatio || 4 // 设置为设备像素比或更高以获得超清效果 
      });  
      const option = {
        title: {  
          text: '夹杂物组成分布',  
          left: 'center',  // 水平居中  
          top: 10,         // 距顶部10px  
          textStyle: {  
            fontSize: 14,  
            fontWeight: 'bold'  
          }  
        }, 
        tooltip: {},
        legend: {},
        grid: {  
          left: '4%',    // 减小左边距  
          right: '4%',   // 减小右边距  
          bottom: '3%', // 为旋转的标签预留底部空间  
          top: '10%',     // 为标题预留顶部空间  
          containLabel: true, // 确保标签被包含在内  
          width: 'auto'  // 自动使用可用宽度  
        },  
        xAxis: {
          data: ["CaF2","CaO","CeO","MgO","Al2O3","Ti2O3","Li2O","TiO2","SiO2","B2O3","V2O3","MnO","NbO2","Cr2O3","FeO","Na2O","K2O","TiN","AlN","CeS","TiS","MnS"],
          axisLabel: {  
            rotate: -45,  
            interval: 0,  
            align: 'left',  
            verticalAlign: 'top',     // 改为top来使标签向下移动  
            margin: 15,               // 增加margin使标签向下移动更多  
            offset: -40,              // 增大负offset值使标签向左移动更多  
            distance: 20,              // 增加距离与轴线的距离 
            fontFamily: '"Times New Roman", serif'
          } 
        },
        yAxis: {
          name: '百分比',
          axisLabel: {  
            fontFamily: '"Times New Roman", serif'
          } 
        },
        series: [{
          type: 'bar',
          data: this.echartsData
        }]
      };
      chart.setOption(option);
    },
//        夹杂物溯源方法    ///////////////////////////////////////////////////////////////////////////////////////////////
    analyzeSource() {  
      if (Object.keys(this.currentItem).length !== 0) {  
          const loading = this.$loading({  
              lock: true,  
              text: '正在分析夹杂物来源...',  
              spinner: 'el-icon-loading',  
              background: 'rgba(0, 0, 0, 0.7)'  
          });  

          service.post('suyuanguize', this.currentItem).then(res => {  
              loading.close();  

              console.log("API调用成功，返回结果:", res); // 添加日志  
              
              if (res.success) {  
                  if (this.analysisResult) {  
                      console.warn("之前的分析结果存在，清除之前的结果。");  
                  }  

                  let resultText = `<strong>【最佳匹配】:</strong>   
                  <div style="text-align: left; font-weight: bold; font-size: 14px; color: red;">${res.result.most_similar}
                      (相似度: ${res.result.similarity_value})  
                  </div> `; 

                  resultText += "<strong>【所有可能来源相似度】:</strong> <br>";  
                  // 先将对象转换为数组并排序  
                  const sortedSimilarities = Object.entries(res.result.similarities)  
                      .sort((a, b) => b[1] - a[1]); // 降序排序  
                  let rank = 1;  
                  for (const [source, similarity] of sortedSimilarities) {  
                      resultText += `${rank}. ${source}: ${similarity}<br>`;  
                      rank++;  
                  } 

                  this.analysisResult = resultText;  
                  this.sourceAnalysis = true;  
              } else {  
                  this.$message.error(res.message || "分析失败");  
              }  
          }).catch(err => {  
              loading.close();  
              this.$message.error("请求失败：" + err.message);  
          });  
      } else {  
          if (this.tableData.length === 0) {  
              this.$message.warning("请先导入数据！");  
          } else {  
              this.$message.warning("请在表格中选择一行数据进行分析！");  
          }  
      }  
  },
  
      // 包装方法，同时触发三个功能  
      handleSourceAnalysis() {  
        // 先调用原有的画图方法  
        this.jzSource();  
        
        // 再调用新的分析方法  
        this.analyzeSource();  
        
        // 最后绘制三元相图  
        this.drawTernaryPlot();  
      }  


  }
};



</script>

<style scoped lang="scss">
.bar-chart {
  margin: 20px;
}
.home {
  blockquote {
    padding: 10px 20px;
    margin: 0 0 20px;
    font-size: 17.5px;
    border-left: 5px solid #eee;
  }
  hr {
    margin-top: 20px;
    margin-bottom: 20px;
    border: 0;
    border-top: 1px solid #eee;
  }
  .col-item {
    margin-bottom: 20px;
  }

  ul {
    padding: 0;
    margin: 0;
  }

  font-family: "open sans", "Helvetica Neue", Helvetica, Arial, sans-serif;
  font-size: 13px;
  color: #676a6c;
  overflow-x: hidden;

  ul {
    list-style-type: none;
  }

  h4 {
    margin-top: 0px;
  }

  h2 {
    margin-top: 10px;
    font-size: 26px;
    font-weight: 100;
  }

  p {
    margin-top: 10px;

    b {
      font-weight: 700;
    }
  }

  .update-log {
    ol {
      display: block;
      list-style-type: decimal;
      margin-block-start: 1em;
      margin-block-end: 1em;
      margin-inline-start: 0;
      margin-inline-end: 0;
      padding-inline-start: 40px;
    }
  }
}

    .el-main {  
      padding: 10px;  
    }  

    .el-card {  
      margin-top: 10px;  
    }  

    /* 调整文本框的样式 */  
    .el-scrollbar__wrap {  
      overflow-x: hidden;  
    }  

    /* 整个滚动条 */  
    .el-table::-webkit-scrollbar {  
      width: 8px;     /* 横向滚动条的宽度 */  
      height: 8px;    /* 纵向滚动条的高度 */  
    }  

    /* 滚动条滑块 */  
    .el-table::-webkit-scrollbar-thumb {  
      background-color: #d6e6f2;  /* 滚动条颜色 */  
      border-radius: 4px;         /* 滚动条圆角 */  
    }  

    /* 滚动条轨道 */  
    .el-table::-webkit-scrollbar-track {  
      background-color: #f0f0f0;  /* 轨道颜色 */  
    }




</style>


